//
//  CommonlyAddressViewController.m
//  XDBaseFrameWork
//
//  Created by xindao on 14-10-28.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "CommonlyAddressViewController.h"
// 自定义cell
#import "AddressCell.h"
// Cell的删除
#import "LeftSwipeDeleteCell.h"


@interface CommonlyAddressViewController ()<UIAlertViewDelegate>
{
    // 添加地址
    UILabel * addMoreAddress;

    UIButton * _deleteButton;
    NSIndexPath * _editingIndexPath;

    UISwipeGestureRecognizer * _leftGestureRecognizer;
    UISwipeGestureRecognizer * _rightGestureRecognizer;
    UITapGestureRecognizer * _tapGestureRecognizer;
    UIImageView * noDataIV;
}
// 可变数组模型
@property(nonatomic, strong)NSMutableArray *addressArray;

@property (nonatomic, strong) LeftSwipeDeleteCell *myTableView;
// 地址模型
@property (nonatomic, strong) AddNewAddress *modelAddress;
@end

@implementation CommonlyAddressViewController

// 地址列表
-(NSMutableArray *)addressArray
{
    if (_addressArray == nil)
    {
        _addressArray = [NSMutableArray array];
    }
    return _addressArray;
}

// 视图即将出现
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getUserAddress];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // 网络请求，获取用户地址。
//    [self getUserAddress];
    self.titleLabel.text = @"常用地址";

    CGRect frame = self.view.bounds;
    self.myTableView = [[LeftSwipeDeleteCell alloc] initWithFrame:frame];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.myTableView registerClass:[AddressCell class] forCellReuseIdentifier:@"Cell"];
    // 去掉分割线
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:self.myTableView];

    // 导航栏添加按钮
    [self navButtonAndOther];

}
// 导航栏添加按钮
- (void)navButtonAndOther
{
    // 右侧添加按钮
    CGFloat jheight = IOS7?20:0;
    addMoreAddress = [UILabel initLabelText:@"添加" andRect:CGRectMake(UI_SCREEN_WIDTH - 45,jheight, 45, 44) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:15] andTextColor:UIColorFromRGB(0xff6800) andTextAlignment:NSTextAlignmentLeft];
    [self.navigationBarView addSubview:addMoreAddress];

    // 左侧“添加”字体 左边的图片
//    UIImageView * jiv = [UIImageView initImageViewRect:CGRectMake(UI_SCREEN_WIDTH - 60,(44-8)/2.0f+aHeight,15,8) andImage:LOADIMAGE(@"cityimg@2x") andUserInteractionEnabled:YES];
//    [self.navigationBarView addSubview:jiv];
    // 添加新地址按钮
    UIButton * addBtn = [self createButtonOnNavigationWithRect:CGRectMake(UI_SCREEN_WIDTH - 50,jheight - 5, 45, 50) normalImg:nil highlightImg:nil];
//    addBtn.backgroundColor = [UIColor grayColor];
    [addBtn addTarget:self action:@selector(chooseBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:addBtn];
}

// 添加新地址按钮
-(void)chooseBtnClick{
    AddNewAddressViewController *addNewAd = [[AddNewAddressViewController alloc] init];
    // 设置下一级代理常代理
    addNewAd.delegate = self;
    [self.navigationController pushViewController:addNewAd animated:YES];
}

// 返回按钮
-(void)backPrePage
{

    [self.navigationController popViewControllerAnimated:YES];

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

// 从模型获取
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 模型返回数据
    return self.addressArray.count;
}

// Cell 的取值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    AddressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (cell == nil){
        cell = [[AddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // 网络数据
    cell.nameLB.text = self.addressArray[indexPath.row][@"Addr"];



    // 默认地址
    if ([self.addressArray[indexPath.row][@"IsDefault"] intValue]== 1) {
        cell.redPointIV.hidden = NO;
    }
    else
        cell.redPointIV.hidden = YES;


    // cell 的选择样式
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //设置输入框内容的字体样式和大小
    cell.textLabel.font = [UIFont fontWithName:@"Arial" size:16.0f];
    //设置字体颜色
    cell.textLabel.textColor = [UIColor blackColor];

    if (!indexPath.row) {
        cell.topView.hidden = NO;
        cell.downView.hidden = YES;

    }else{
        cell.topView.hidden = NO;
        cell.downView.hidden = YES;
    }

    return cell;
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// 删除  默认 的设置
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
       // 网络数据
        NSString *addrID = self.addressArray[indexPath.row][@"AddrID"];
        // 网络调用
        [self deleteAddress:addrID];

    }
    else if (editingStyle == UITableViewCellEditingStyleNone)
    {

    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}



// 获得 用户常用地址 网络请求
-(void)getUserAddress
{
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID];
    NSDictionary *dic = @{ @"CustomerID": userID};
    [self getDataWithDict:dic api:API_customer_address];
}
// 发送网络请求，添加地址。
-(void)getDataWithDict:(NSDictionary *)dict api:(NSString *)api
{

    if (![XDTools NetworkReachable]) {
        noDataIV.hidden = NO;
        _myTableView.hidden = YES;
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }

    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];

    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];

        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];

        if([[tempDic objectForKey:@"status"]intValue] == 1){
            if ([api isEqualToString:API_customer_address]) {

                // 移除所有地址
                [self.addressArray removeAllObjects];
                // 到数组里面添加地址字典
                if(!ARRAY_IS_NOT_EMPTY(tempDic[@"data"][@"list"])){
                    noDataIV.hidden = NO;
                    _myTableView.hidden = YES;
                    return ;
                }
                [self.addressArray addObjectsFromArray:tempDic[@"data"][@"list"]];


                // 从新加载一次数据
                [self.myTableView reloadData];

            }else{
                noDataIV.hidden = NO;
                _myTableView.hidden = YES;

            }

        }else{
            noDataIV.hidden = NO;
            _myTableView.hidden = YES;
//            [XDTools showTips:tempDic[@"msg"] toView:self.view];

        }
        
    }];
    
    [request setFailedBlock:^{
        noDataIV.hidden = NO;
        _myTableView.hidden = YES;
        [XDTools hideProgress:self.contentView];
    }];

    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}



// 删除常用地址
-(void)deleteAddress:(NSString *)addrID
{
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID];
//    NSString *AddrID = [NSString stringWithFormat:nil];
    NSDictionary *dic = @{ @"CustomerID": userID, @"AddrID": addrID};
    [self DeleteDataWithDict:dic api:API_delDefault_address];
}
// 发送网络请求，删除常用地址。
-(void)DeleteDataWithDict:(NSDictionary *)dict api:(NSString *)api
{

    if (![XDTools NetworkReachable]) {
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }

    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];

        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];

//        [XDTools showTips:tempDic[@"msg"] toView:self.contentView];


        if([[tempDic objectForKey:@"status"]intValue] == 1){

            if ([api isEqualToString:API_delDefault_address]) {

//                [XDTools showTips:@"删除地址成功" toView:self.contentView];

                // 得到用户地址
                [self getUserAddress];

            }else{

            }

        }else{
//            [XDTools showTips:tempDic[@"msg"] toView:self.view];

        }

    }];
    
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}



// 设置默认地址
-(void)setDefaultAddress:(NSString *)addrID
{
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID];
    NSDictionary *dic = @{ @"CustomerID": userID, @"AddrID": addrID};
    [self getSetDataWithDict:dic api:API_default_address];
}
// 发送网络请求，设置默认地址。
-(void)getSetDataWithDict:(NSDictionary *)dict api:(NSString *)api
{

    if (![XDTools NetworkReachable]) {
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }

    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];

        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];

        if([[tempDic objectForKey:@"status"]intValue] == 1){

            if ([api isEqualToString:API_default_address]) {

//                [XDTools showTips:@"设置默认地址地址成功" toView:self.contentView];

                // 刷新得到用户地址
                [self getUserAddress];


            }else{

            }

        }else{
//            [XDTools showTips:tempDic[@"msg"] toView:self.view];

        }

    }];

    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}



// 选择一行调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

      [self.myTableView deselectRowAtIndexPath:indexPath animated:YES];


        UIActionSheet* sheet1 = [[UIActionSheet alloc] initWithTitle:nil delegate:self

                                                   cancelButtonTitle:@"取消"

                                              destructiveButtonTitle:nil

                                                   otherButtonTitles:@"设置成默认地址",@"删除地址",nil];


// 设置tag值 （tag值就是选中的row）
        sheet1.tag = indexPath.row ;
        [sheet1 showInView:[self view]];

}


// 代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    NSIndexPath* indexpath = [NSIndexPath indexPathForRow:actionSheet.tag inSection:0];

        if (buttonIndex == 1) {

            // 删除地址
        // 网络数据
        NSString *addrID = self.addressArray[indexpath.row][@"AddrID"];
        // 网络调用
        [self deleteAddress:addrID];


        }else if(buttonIndex == 0) {

        NSString *addrID = self.addressArray[indexpath.row][@"AddrID"];

        // 调用网络请求
        [self setDefaultAddress:addrID];

        }

}


// 设置字体颜色
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet

{
    for (UIView *subViwe in actionSheet.subviews) {

        if ([subViwe isKindOfClass:[UIButton class]]) {

            UIButton *button = (UIButton*)subViwe;

            [button setTitleColor:[UIColor colorWithRed:1.0 green:0 blue:0 alpha:1] forState:UIControlStateNormal];
            break;
            
        }
        
    }
    
}



@end
